from django.db.models import Q, Sum
from django.shortcuts import render
from rest_framework.response import Response

from video.models import Videos
from .models import Play
from .serializer import PlayDetailSerializer, PlaySerializer
from rest_framework import status, viewsets


# Create your views here.


class PlayViewSet(viewsets.ModelViewSet):
    serializer_class = PlaySerializer

    def get_queryset(self):
        queryset = Play.objects.all()
        params = self.request.query_params
        if params:
            filters = {}
            for key, value in params.items():
                filters[key] = value
            queryset = queryset.filter(**filters)
        return queryset

    def get_play_count(self, request, *args, **kwargs):
        video_id = kwargs.get('pk')  # 从URL参数中获取视频的ID
        filters = Q(video_id=video_id)
        play_count = Play.objects.filter(filters).aggregate(sum_plays=Sum('count'))  # 查询播放数量
        play_count = play_count['sum_plays']
        return Response({'play_count': play_count}, status=status.HTTP_200_OK)

    def search_videos(self, request, *args, **kwargs):
        title = request.query_params.get('title', None)
        page = int(request.query_params.get('page', 0))

        # 获取开始索引和结束索引

        start_index = page * 10
        end_index = start_index + 10

        # 过滤视频
        videos = queryset = Play.objects.values(
            'video_id', 'video__cover_path', 'video__file_path',
            'video__title', 'video__mup__username','video__mup_id'
        ).filter(video__title__icontains=title).filter(video__status=True).annotate(sum_plays=Sum('count')).order_by('-sum_plays')

        total_count = videos.count()
        if start_index >= total_count:
            return Response({'recommendations': [], 'total': total_count}, status=status.HTTP_200_OK)
        elif end_index > total_count:
            end_index = total_count

        results = list(videos[start_index:end_index])

        return Response({'videos': results, 'total': total_count}, status=status.HTTP_200_OK)


class PlayDetailViewSet(viewsets.ModelViewSet):
    serializer_class = PlayDetailSerializer

    def get_queryset(self):
        queryset = Play.objects.all()
        params = self.request.query_params
        if params:
            filters = {}
            for key, value in params.items():
                filters[key] = value
            queryset = queryset.filter(**filters)
        return queryset

    def get_play_history(self, request, *args, **kwargs):
        user_id = kwargs.get('user_id')
        num = kwargs.get('num')
        from_index = kwargs.get('from')
        play_history = Play.objects.filter(user_id=user_id).order_by('-time')
        result = []
        index = 0
        for i in range(from_index, from_index + num):
            if i >= len(play_history):
                break
            result.append(PlayDetailSerializer(play_history[i]).data)
            index += 1
        return Response({'plays': result, 'count': len(play_history)}, status=status.HTTP_200_OK)

    def get_recommendations(self, request, *args, **kwargs):
        try:
            page = int(request.query_params.get('page', 0))
        except ValueError:
            page = 0

        video_type = request.query_params.get('type', None)

        start_index = page * 10
        end_index = start_index + 10

        queryset = Play.objects.values(
            'video_id', 'video__cover_path', 'video__file_path',
            'video__title', 'video__mup__username', 'video__status','video__mup_id'
        ).filter(video__status=True).annotate(sum_plays=Sum('count')).order_by('-sum_plays')

        if video_type:
            queryset = queryset.filter(video__type=video_type)
        total_count = queryset.count()

        if start_index >= total_count:
            return Response({'recommendations': [], 'total_count': total_count}, status=status.HTTP_200_OK)
        elif end_index > total_count:
            end_index = total_count

        recommendations = list(queryset[start_index:end_index])

        return Response({'recommendations': recommendations, 'total_count': total_count}, status=status.HTTP_200_OK)

    def get_top_videos_by_type(self, request, *args, **kwargs):
        types = Videos.objects.values_list('type', flat=True).distinct()
        top_videos = []

        for video_type in types:
            top_video = Play.objects.filter(video__type=video_type).values(
                'video_id', 'video__cover_path', 'video__file_path',
                'video__title', 'video__mup__username', 'video__type', 'video__status','video__mup_id'
            ).filter(video__status=True).annotate(sum_plays=Sum('count')).order_by('-sum_plays').first()
            if top_video:
                top_videos.append(top_video)

        return Response({'top_videos': top_videos}, status=status.HTTP_200_OK)

    def search_videos(self, request, *args, **kwargs):
        title = request.query_params.get('title', None)
        page = int(request.query_params.get('page', 0))

        # 获取开始索引和结束索引

        start_index = page * 10
        end_index = start_index + 10

        # 过滤视频
        videos = queryset = Play.objects.values(
            'video_id', 'video__cover_path', 'video__file_path',
            'video__title', 'video__mup__username', 'video__status','video__mup_id'
        ).filter(video__title__icontains=title).filter(video__status=True).annotate(sum_plays=Sum('count')).order_by('-sum_plays')

        total_count = videos.count()
        if start_index >= total_count:
            return Response({'recommendations': [], 'total': total_count}, status=status.HTTP_200_OK)
        elif end_index > total_count:
            end_index = total_count

        results = list(videos[start_index:end_index])

        return Response({'videos': results, 'total': total_count}, status=status.HTTP_200_OK)
